﻿App.addNewPage({
	id: 'logon',
	url: '/Home/Logon',
	require: ['signalr', 'alert'],
	title: '',
	init: function () {

		if (!App.isSupported()) {
			$.UIkit.notify({
				message: '<i class="uk-icon-warning"></i> {message}'.replace('{message}', Localization.BrowserProblem),
				status: 'warning',
				timeout: 5000,
				pos: 'top-center'
			});
		}

		var $cont = $('.page-container'),
			$form = $('#logon-form'),
			$submitButton = $('#submit-button');

		$(document.body).removeAttr('style');

		$('.social-likes').socialLikes();

		$form.bind('keyup keypress', function (e) {
			var code = e.keyCode || e.which;
			if (code == 13) {
				e.preventDefault();
				$submitButton.click();
				return false;
			}
			return true;
		}).validate({
			rules: {
				name: {
					required: true,
					minlength: 3,
					maxlength: 15
				}
			},
			messages: {
				name: {
					required: Localization.NameValidationRequired,
					minlength: Localization.NameValidationMinLength,
					maxlength: Localization.NameValidationMaxLength
				}
			},
			showErrors: function (map, list) {
				TweenMax.killTweensOf($submitButton);

				if (!App.isUndefined(map.name)) {
					$submitButton.addClass('uk-button-danger').text(map.name);
					TweenMax.to($submitButton, 1, {
						delay: 3,
						className: '-=uk-button-danger',
						ease: Elastic.easeOut,
						onStart: function () {
							$submitButton.removeClass('uk-button-danger').text('Представиться!');
						}
					});
				}

				this.defaultShowErrors();
			},
			errorPlacement: function (e, el) { return true; },
			errorClass: 'uk-form-danger',
			onsubmit: false,
			onfocusout: false,
			onkeyup: false,
			onclick: false,
			focusCleanup: true
		});

		$(window).unbind('beforeunload');

		if ($cont.css('opacity') == 0) {
			TweenMax.set($cont, { scale: 0.5 });
			TweenMax.set($cont, { scale: 1 });
			TweenMax.to($cont, 0.5, { opacity: 1, onComplete: function () { $form.find('input[type=text]').focus(); } });
		}

		function getFormData() {
			var formObj = {};
			var inputs = $form.serializeArray();
			$.each(inputs, function (i, input) {
				formObj[input.name] = input.value;
			});
			return formObj;
		}

		$submitButton.click(function () {
			if (!$form.valid()) return;

			$('#overlay').show();
			
			App.debug ? App.emptyFn() : $.connection.hub.url = 'http://api.drawpi.co/signalr';

			App.signalr.start().done(function () {
				App.signalr.server({
					hub: 'gameHub',
					action: 'initializeUser',
					data: JSON.stringify(getFormData())
				}).fail(function (e) {
					App.alert.warning(Localization.ConnectionError);
					console.log('logon.page.js', e);
				}).done(function (r) {
					if (App.isUndefined(r)) return;
					App.user.init(r);
					App.goToPage('intro');
				});
			});
		});
	}
});